import { defineStore } from 'pinia'
import { store } from '@/store'
import type { AppState, RouterItem } from '@/store/types'
// 引入接口
import { authLogin, getRouters } from '@/api/sys'
import { HTTP_SUCCESS_CODE } from "@/config/vars"
import { useCache } from "@/hooks/useCache"
// 引入工具
import { buildRouters } from '@/utils/menu'
const { wsCache } = useCache()


// 默认AppState参数
export const appModules: AppState = {
  token: "token", // token标识
  permissionBtns: [], // 所有按钮权限
  isAddRouters: false, // 是否动态添加过路由
  routes: [], // 所有路由
}

export const useAppStore = defineStore({
  id: "app",
  state: (): AppState => appModules,
  getters: {
    getToken(): string {
      return this.token
    },
    getPermissionBtns(): string[] {
      return this.permissionBtns
    },
    getIsAddRouters(): boolean {
      return this.isAddRouters
    },
    getRoutes(): RouterItem[] {
      return this.routes
    }
  },
  actions: {
    setToken(token: string) {
      this.token = token
    },
    setPermissionBtns(btns: string[]) {
      this.permissionBtns = btns
    },
    setIsAddRouters(isAddRouters: boolean) {
      this.isAddRouters = isAddRouters
    },
    setRoutes(routes: RouterItem[]) {
      this.routes = routes
    },

    login(params: any) {
      return new Promise((resolve, reject) => {
        authLogin(params).then((res: any) => {
          if (res?.code == HTTP_SUCCESS_CODE) {
            let { access_token } = res.data;
            // 保存token
            wsCache.set(this.token, access_token)
            resolve(res)
          } else {
            reject(res)
          }
        }).catch(err => {
          console.log("err", err)
          resolve(err)
        })
      })
    },
    generateRoutes() {
      return new Promise((resolve, reject) => {
        getRouters().then((res: any) => {
          // console.log("getRouters", res);
          if (res?.code == HTTP_SUCCESS_CODE) {
            let data = res.data;
            let routers = buildRouters(data)
            console.log("routers", routers);
            resolve({})
          } else {
            resolve(res)
          }
        }).catch(err => {
          resolve(err)
        })
      })
    }
  }
})

export const useAppStoreFn = () => {
  return useAppStore(store)
}